﻿using System;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using InvoiceChecking.Data;
using InvoiceChecking.Entities;

public partial class Admin_ExportJournalVoucher : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void grv_BatchList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grv_PaymentList.PageIndex = e.NewPageIndex;
        BindData();
    }
    protected void btn_Filter_Click(object sender, EventArgs e)
    {
        BindData();
    }

    private void BindData()
    {
        string whereExpression = BuildWhereExpression();
        int count;
        var vouchers = DataRepository.SunJournalVoucherProvider.GetPaged(whereExpression, "VoucherNo", 0, 1000, out count);
        lbl_Error.Text = count == 0 ? "No data. Please check the filter expression" : "";
        grv_PaymentList.RecordsCount = count;
        grv_PaymentList.DataSource = vouchers;
        grv_PaymentList.DataBind();
    }

    private string BuildWhereExpression()
    {
        string whereExpression = "";
        if (!string.IsNullOrEmpty(tb_VoucherDateFrom.Text))
        {
            if (!string.IsNullOrEmpty(tb_VoucherDateTo.Text))
                whereExpression += string.Format("Transaction_dt BETWEEN '{0} 00:00:00' AND '{1} 23:59:59'", tb_VoucherDateFrom.Text,
                                                    tb_VoucherDateTo.Text);
            else
                whereExpression += string.Format("DATEDIFF(d,Transaction_dt,'{0}')'", tb_VoucherDateFrom.Text);
            if (!string.IsNullOrEmpty(tb_JournalIdFrom.Text) && !string.IsNullOrEmpty(tb_JournalIdTo.Text))
            {
                whereExpression += string.Format(" AND VoucherNo BETWEEN '{0}' AND '{1}'", tb_JournalIdFrom.Text, tb_JournalIdTo.Text);
            }
            if (ddl_PreparedBy.SelectedIndex > 0)
                whereExpression += string.Format(" AND PreparedBy ='{0}'", ddl_PreparedBy.SelectedValue.Substring(0, 5));
        }


        return whereExpression;
    }
    protected void grv_BatchList_ExcelBeforeFormat(object sender, InvoiceChecking.Web.UI.ExcelFormatEventArgs e)
    {
        BindData();
    }

    protected void btn_Export_Click(object sender, EventArgs eventArgs)
    {
        BindData();
        ExportToExcel();
    }
    protected void ExportToExcel()
    {
        string authUserName = Context.User.Identity.Name.Split('\\')[1];
        string whereExpression = string.Format("JournalVoucherId in (Select VoucherNo from SunJournalVoucher Where Transaction_dt BETWEEN '{0} 00:00:00' AND '{1} 23:59:59') AND PreparedBy ='{2}'", tb_VoucherDateFrom.Text,
                                                tb_VoucherDateTo.Text, ddl_PreparedBy.SelectedValue.Substring(0, 5));
        int count;
        var exportList = DataRepository.JournalVoucherProvider.GetPaged(whereExpression, "", 0, 10000, out count);
        foreach (var journal in exportList)
        {
            journal.ExportedDate = DateTime.Now;
            journal.ExportedBy = authUserName;
        }
        DataRepository.JournalVoucherProvider.Update(exportList);
        //Response.Clear();
        //Response.AddHeader("content-disposition", "attachment;filename=SunPayment" + tb_VoucherDateFrom.Text + tb_VoucherDateTo.Text + ".xls");
        //Response.Charset = "";
        //Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //Response.ContentType = "application/vnd.xls";
        //var stringWrite = new System.IO.StringWriter();
        //var htmlWrite = new HtmlTextWriter(stringWrite);
        //grv_PaymentList.RenderControl(htmlWrite);
        //string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        //Response.Write(style);
        //Response.Output.Write(stringWrite.ToString());
        //lbl_Error.Text = stringWrite.ToString();
        //Response.End();
        Response.Clear();
        Response.Buffer = true;

        Response.AddHeader("content-disposition", "attachment;filename=SunPayment" + tb_VoucherDateFrom.Text + tb_VoucherDateTo.Text + ".xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        for (int i = 0; i < grv_PaymentList.Rows.Count; i++)
        {
            GridViewRow row = grv_PaymentList.Rows[i];

            //Apply text style to each Row
            for (int j = 0; j < row.Cells.Count; j++)
            {
                if (j > 7)
                    row.Cells[j].Attributes.Add("class", "textmode");
            }
        }
        grv_PaymentList.RenderControl(hw);
        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }
    protected void ddl_PaymentType_SelectedIndexChanged(object sender, EventArgs e)
    {
        btn_Filter_Click(btn_Filter, null);
    }
}
